<template>
  <view class="bodyView">
    <!-- 用户头像信息 -->
    <view class="UserDataList">
      <view style="display: flex;align-items: center">
        <u-avatar @click="deleteRoom" :src="IMG_URL + ownerAvatar" size="100"></u-avatar>
        <view class="userView" style="margin-left: 10rpx;">
          <view class="fontName">{{ ownerNickname }}</view>
          <view style="font-size: 24rpx;color: #cecece">点击头像删除房间</view>
        </view>
      </view>
      <view class="discount" style="">当前{{discount}}折</view>

    </view>

    <!-- 用户添加帮组 -->
    <view style="margin: 50rpx;" class="imgView">
      <view v-for="(item,index) in 9" :key="index">
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center"
             v-if="roomData[item].avatar">
          <div class="img-box1">
            <image @click="delUser(roomData[item])" class="userImg" mode="aspectFill"
                   :src="IMG_URL + roomData[item].avatar"></image>
          </div>
          <div style="width: 120rpx;overflow: hidden;text-overflow: ellipsis;text-align: center">
            {{ roomData[item].nickname }}
          </div>
        </div>

        <div v-else style="display: flex;flex-direction: column;justify-content: center;align-items: center">
          <div class="img-box2">
            <image mode="aspectFill" class="userImg" src="/static/image/swiper/jiahao.png"></image>
          </div>
          <div style="width: 120rpx;height: 20rpx;overflow: hidden;text-overflow: ellipsis;text-align: center"></div>
        </div>

      </view>
    </view>

    <button :disabled="roomData.length>=9" class="btn" open-type="share">{{ `邀请好友(${roomData.length}/9)` }}</button>

    <!-- 提示 -->
    <view class="titleMsg">
      <p class="title">折扣规则</p>
      <hr style="border: 1px dashed #ccc; width: 100%;height: 1px;"/>
      <view
          style="width: 100%;height: 50rpx; display: flex; align-items: center; justify-content: center; text-align: center;">
        <view
            style="width: 350rpx; text-align: center; background-color: hotpink; border-radius: 20rpx; color: aliceblue;">
          如有疑问请联系官方客服
        </view>
      </view>
      <scroll-view scroll-y="true" class="scroll-Y">
        <view style=" width: 94%; height: 150rpx; margin: 20rpx 420rpx 20rpx 20rpx;">
          <view >【特别提示】用户加互娱师一共:</view>
          <view  style="font-weight: bolder;margin-top: 15rpx;margin-left: 15rpx" v-for="(item,index) in getText" :key="index">{{ item.size }}人{{ item.discount * 10 }}折</view>
        </view>
      </scroll-view>
    </view>
    <!-- 邀请的互娱师 -->
    <view class="getPlayer" :class="[item.sex == 2 ? 'boy' : 'girl']" v-for="(item,index) in userList" :key="index">
      <image mode="aspectFill" class="imageContent" :src="IMG_URL + item.avatar"></image>
      <view class="UserTagTitle">
        <view class="UserMsgData">
          <view class="nameFont" :class="[item.sex == 2 ? 'boyMoney':'girlMoney']">{{ item.name }}</view>
          <view class="ageFont" :class="[item.sex == 2 ? 'boyMoney':'girlMoney']" style="margin-left: 10rpx;">
            {{ item.age }}岁
          </view>
        </view>

        <!-- 个性签名 -->
        <view>
          <view class="brieflyFont">
            <p>{{ item.signature }}</p>
          </view>
        </view>
        <view class="tag-user">
          <view class="tag">
            <u-tag color="white" bg-color="#FF7F50" border-color="#FF7F50" :text="item.title[0]"
                   type="success" size="mini"></u-tag>
          </view>
          <view class="tag">
            <u-tag color="white" bg-color="#FF7F50" border-color="#FF7F50" :text="item.title[1]"
                   type="success" size="mini"></u-tag>
          </view>
        </view>
        <!-- 金额数目 -->
        <view class="boxWarp">
          <view class="boxWarpMoney" :class="[item.sex == 2 ? 'boyMoney':'girlMoney']">
            <image class="imagePlayer" mode="aspectFit" :src="[item.sex == 2 ? imgBlue : imgPink]"></image>
            {{ item.price + "币/小时" }}
          </view>
        </view>
      </view>
      <view class="buttonUserView">
        <view @click="invite(item)" class="helpBt" :class="[item.sex] == 2 ? 'bt-boy':'bt-girl'">
          邀请
        </view>
      </view>
    </view>
    <!-- 立享折扣下单 -->
    <view class="zutuanyouhui">
      <view v-if="isOwner" @click="orders" class="BTN-Font">立享折扣下单</view>
      <view v-else @click="quit" class="BTN-Font">退出房间</view>
    </view>
  </view>
</template>

<script>
import {OfflineGamer} from "../../api/gamer.js"
import {getText} from "../../api/group.js"
import {createRoom, delRoom, joinRoom, delUser, getRoomByUserId, inviteGamer, quitRoom} from "../../api/room";
import {createOrder} from "../../api/order";
import {getGamerByUserId} from "../../api/gamer.js";
import {IMG_URL} from "../../config/URL";

export default {
  onUnload() {
    this.socketTask.close({
      success: (e) => {
        console.log('连接断开', e)
      }
    })
  },
  async onLoad(option) {

    // 开启webSocket连接
    this.socketTask = uni.connectSocket({
      url: `wss://www.zhuhaiziyue.com/ziyue/websocket/${uni.getStorageSync('userInfo').id}`,
      complete: () => {
      }
    })
    this.socketTask.onMessage(async e => {
      this.roomData = JSON.parse(e.data).members;

      const room = await getRoomByUserId({
        checkId: uni.getStorageSync('userInfo').id
      });
      console.log(room, '这是room')
      if (room.data.code == 500) {
        console.log(room, '这是返回值是500的room')
        uni.showModal({
          title: '提示',
          content: '您已被踢出房间',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              uni.switchTab({url: '/pages/Home/Home'})
            } else if (res.cancel) {
            }
          }
        });
      }
    })

    let {roomId, type} = JSON.parse(decodeURIComponent(option.data))

    uni.showLoading({
      title: "加载中"
    });

    //根据传过来的房间id跳转
    const res = await joinRoom({
      roomId
    })

    if (res.data.code == 500) {
      uni.showModal({
        title: '提示',
        content: res.data.msg,
        showCancel: false,
        success: async function (res) {
          if (res.confirm) {
            const del = await delRoom()
            uni.switchTab({url: '/pages/Home/Home'})
          } else if (res.cancel) {
            uni.switchTab({url: '/pages/Home/Home'})
          }
        }
      });
      uni.hideLoading();
      return
    }
    res.data.data.owner == uni.getStorageSync('userInfo').id ? this.isOwner = true : this.isOwner = false
    this.ownerAvatar = res.data.data.ownerAvatar
    this.ownerNickname = res.data.data.ownerNickname
    this.roomData = res.data.data.members
    let haveGamer = false
    this.roomData.map(e => {
      if (e.isGamer) {
        haveGamer = true
        return
      }
    })
    if (haveGamer && this.roomData.length >= 3) {
      this.allowOrder = true
    }
    uni.hideLoading();
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"]
    });

  },

  // 分享帮组链接
  async onShareAppMessage(res) {

    const room = await getRoomByUserId({
      checkId: uni.getStorageSync('userInfo').id
    });

    let data = {
      type: 'join',
      roomId: room.data.data,
    }
    return {
      title: '邀请好友助力',
      // path: '/pages/group_detail/group_detail?id=' + this.id + '?pid=' + this.infoList.user.id,
      path: '/subPages/group/group?data=' + encodeURIComponent(JSON.stringify(data)),
      success: (res) => {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  },

  async created() {
    let userInfo = uni.getStorageSync('userInfo')
    this.name = userInfo.nickname
    this.userInfo = userInfo
    const res = await OfflineGamer({
      page: 1,
      limit: 10,
	  sex:userInfo.sex,
    })
    this.userList = res.data.data
    // 规则
    const title = await getText()
    this.getText = title.data.data
  },
  data() {
    return {
      IMG_URL,
      socketTask: {},
      isOwner: false,
      allowOrder: false,
      // 互娱师数据
      userInfo: {},
      roomData: [],
      ownerAvatar: '',
      ownerNickname: '',
      // 返回顶部
      scroll: 0,
      name: "请登录",
      imgBlue: "/static/image/userDetails/boyCoin.png",
      imgPink: "/static/image/userDetails/girlCoin.png",
      userList: [],
      getText: [],
    }
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  methods: {
    //踢出房间
    async delUser(item) {
      let that = this
      uni.showModal({
        title: '提示',
        content: '是否踢出房间',
        success: async function (res) {
          if (res.confirm) {
            console.log(item, '这是要删除的用户的id')
            const res = await delUser({
              kickId: item.id
            })
            console.log(res, '调用删除接口后的返回值')
            if (res.data.code == 500) {
              uni.showToast({
                title: '您不是房主',
                duration: 3000,
                icon: 'none',
              });
              return
            } else {
              that.roomData = res.data.data.members
              let haveGamer = false
              that.roomData.map(e => {
                if (e.isGamer) {
                  haveGamer = true
                  return
                }
              })
              if (haveGamer && that.roomData.length >= 3) {
                that.allowOrder = true
              }
              uni.showToast({
                title: '删除成功',
                duration: 3000,
                icon: 'none',
              });
            }
          } else if (res.cancel) {

          }
        }
      });

    },

    //邀请
    async invite(item) {
      uni.showLoading({
        title: "邀请中"
      })

      const room = await getRoomByUserId({
        checkId: uni.getStorageSync('userInfo').id
      });

      console.log(room.data.data)

      const res = await inviteGamer({
        gamerId: item.id,
        roomId: room.data.data
      })
      if (res.data.code == 500) {
        uni.showToast({
          title: res.data.msg,
          duration: 3000,
          icon: 'none',
        });
      } else {
        this.roomData = res.data.data.members;
        let haveGamer = false
        this.roomData.map(e => {
          if (e.isGamer) {
            haveGamer = true
            return
          }
        })
        if (haveGamer && this.roomData.length >= 3) {
          this.allowOrder = true
        }
        uni.showToast({
          title: '邀请成功',
          duration: 3000,
          icon: 'none',
        });
      }
      uni.hideLoading();
    },

    //下单
    async orders() {

      if (!this.allowOrder) {
        uni.showToast({
          title: '未满足下单要求',
          duration: 3000,
          icon: 'none',
        });
        return
      }

      uni.showLoading({
        title: "下单中"
      })
      console.log(this.roomData)
      let userIds = []
      let gamerIds = []
      let Ids = []
      let num = ''
      this.roomData.map(e => {
        if (e.isGamer == true) {
          gamerIds.push(e.id)
        } else {
          userIds.push(e.id)
        }
      })
      for await (let e of gamerIds) {
        const res = await getGamerByUserId({
          id: e
        })
        num += res.data.data.price
        Ids.push(res.data.data.id)
      }
      console.log(num)
      uni.showModal({
        title: '提示',
        content: `本次下单将花费${num}子曰币，是否继续`,
        success: async function (res) {
          if (res.confirm) {
            const res = await createOrder({
              userIds: userIds.join(','),
              gamerIds: Ids.join(','),
            });
            if (res.data.code == 500) {
              uni.showToast({
                title: res.data.msg,
                duration: 3000,
                icon: 'none',
              });
            } else {
              uni.showToast({
                title: '下单成功',
                duration: 3000,
                icon: 'none',
              });
              setTimeout(async () => {
                const del = await delRoom()
                uni.switchTab({url: '/pages/Home/Home'})
              }, 1000)
            }
          } else if (res.cancel) {
          }
        }
      });
      uni.hideLoading();
    },

    //退出房间
    async quit() {
      const room = await getRoomByUserId({
        checkId: uni.getStorageSync('userInfo').id
      });

      uni.showModal({
        title: '提示',
        content: '是否退出房间',
        success: async function (res) {
          if (res.confirm) {
            const res = await quitRoom({
              roomId: room.data.data
            })
            if (res.data.code == 500) {
              uni.showToast({
                title: res.data.msg,
                duration: 3000,
                icon: 'none',
              });
              return
            } else {
              uni.showToast({
                title: '退出成功',
                duration: 3000,
                icon: 'none',
              });
              uni.switchTab({url: '/pages/Home/Home'})
            }
          } else if (res.cancel) {

          }
        }
      });
    },

    //房主删除房间
    async deleteRoom() {
      // const asd =  await delRoom()
      let that = this
      uni.showModal({
        title: '提示',
        content: '是否删除房间',
        success:async function (res) {
          if (res.confirm) {
            that.socketTask.close({
              success: (e) => {
                console.log('连接断开', e)
              }
            })
            const del =  await delRoom()
            uni.showToast({
              title: '下单成功',
              duration: 3000,
              icon: 'none',
            });
            uni.switchTab({url: '/pages/Home/Home'})
          } else if (res.cancel) {}
        }
      });
    }
  },
  computed: {
    discount() {
      let isGamer = false
      this.roomData.map(e => {
        if (e.isGamer) {
          isGamer = true
          return
        }
      })
      if (isGamer) {
        switch (this.roomData.length + 1) {
          case 0:
            return 0
          case 1:
            return 0
          case 2:
            return 0
          case 3:
            return 9.9
          case 4:
            return 9.5
          case 5:
            return 9.3
          case 6:
            return 9
          case 7:
            return 8.5
          case 8:
            return 8
          case 9:
            return 7.5
        }
      } else {
        return 0
      }
    }
  }
}
</script>

<style lang="scss">
//@font-face {
//  font-family: myFont1;
//  src: url("../../lib/RuiZiBangHeiJian-2.otf");
//}
.discount{
  margin-right: 20rpx;
  color: #ec1d23;
  //font-family: myFont1;
  font-size: 58rpx;
  font-weight: bolder;
}
.helpBt {
  text-align: center;
  width: 110rpx;
  height: 80rpx;
  border-radius: 30rpx;
  background-color: #6CC7E2;
  color: white;
  line-height: 80rpx;
  margin-right: 20rpx;
}

.bodyView {
  margin-bottom: 120rpx;
  min-height: 100vh;
  background-image: linear-gradient(#fcfcfc, #eca5a8);

  .btn {
    width: 90%;
    color: white;
    border-radius: 50rpx;
    background-color: rgb(35, 216, 110);
    margin-bottom: 20rpx;
  }
}

.BTN-Font {
  box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
  bottom: 20rpx;
  position: fixed;
  width: 500rpx;
  height: 120rpx;
  text-align: center;
  background-color: #fdfdfd;
  font-size: 60rpx;
  line-height: 120rpx;
  color: #ec1d23;
  border-radius: 60rpx;
}

.zutuanyouhui {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.brieflyFont {
  position: relative;
  left: 1%;
  height: 25rpx;
  width: 250rpx;
  font-size: 20rpx;
  margin: 10rpx;
  overflow: hidden;
  /*让长段文本不换行*/
  white-space: nowrap;
  /*设置文本超出元素宽度部分隐藏*/
  overflow-x: hidden;
  /*设置文本超出部分用省略号显示*/
  text-overflow: ellipsis;
}



.bt-boy {
  color: white;
  background-color: #6CC7E2;
}

.bt-girl {
  color: white;
  background-color: #EFA7D2;
}

.boy {
  background: linear-gradient(white, #6CC7E2);
}

.girl {
  background: linear-gradient(white, #EFA7D2);
}

// 金额色彩
.boyMoney {
  color: #09B6EA;
}

.girlMoney {
  color: #FF1493;
}

.boxWarpMoney {
  height: 50rpx;
  font-size: 1rem;
  display: flex;
  align-items: center;
  margin-left: 15rpx;
}

.buttonUserView {
  justify-content: center;
  height: 100%;
  align-items: center;
  display: flex;
}

.imagePlayer {
  width: 50rpx;
  height: 120rpx;
}

.nameFont {
  font-size: 40rpx;
}

.UserMsgData {
  width: 250rpx;
  height: 80rpx;
  display: flex;
  margin: 10rpx;
  align-items: center;
}

.avaImage {
  width: 120rpx;
}


.UserDataList {
  justify-content: space-between;
  display: flex;
  align-items: center;
  padding: 20rpx;
}

.fontName {
  font-size: 40rpx;
}

.tag-user {
  display: flex;
}

.tag {
  margin: 10rpx;
}

.imgView {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;
}

.img-box2 {
  width: 120rpx;
  height: 120rpx;
  border-radius: 100rpx;
  margin: 20rpx 30rpx;
  border: 1rpx solid #8f8e90;
  background-color: #e4e5e8;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;

  .userImg {
    width: 50%;
    height: 50%;
  }

  .msg {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.img-box1 {
  width: 120rpx;
  height: 120rpx;
  border-radius: 100rpx;
  margin: 10rpx 30rpx;
  border: 1rpx solid #8f8e90;
  background-color: #e4e5e8;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;

  .userImg {
    width: 100%;
    height: 100%;
  }

  .msg {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.titleMsg {
  border-radius: 60rpx;
  border: 2rpx solid;
  margin: 30rpx;
  height: 350rpx;
  overflow: scroll;
}

.title {
  text-align: center;
  line-height: 80rpx;
  font-size: 50rpx;
}

.imageContent {
  border-radius: 20rpx;
  width: 40%;
  height: 100%;
}

.getPlayer {
  display: flex;
  margin: 30rpx;
  height: 250rpx;
  border-radius: 20rpx;
}

.UserTagTitle {
  width: 50%;
}

.boxWarp {
  width: 100%;
  justify-content: right;
}
</style>
